const fs = require('fs')
const puppeteer = require('puppeteer')
const json2xls =  require('json2xls')
const stocks = require('./stock-code.json')
const maxPE = 100
async function main() {
    // Do something
    const browser = await puppeteer.launch({
        headless: true,
    })
    const matches = []
    const page = await browser.newPage()
    const stockCodes = Object.keys(stocks)
    try {
        for (let i = 0; i < stockCodes.length; i++) {
            const stockId = stockCodes[i]
            if (!stockId || /hk/gi.test(stockId)) {
                continue;
            }
            const url = `https://xueqiu.com/S/${stockId}`
            console.log(i + 1, ':', stockId)
            await page.goto(url)
            const item = await page.evaluate(() => {
                const price = document.getElementsByClassName('stock-current')[0].innerText.replace('¥','')
                const stockChange = document.getElementsByClassName('stock-change')[0].innerText.split(' ')
                const info = document.getElementsByClassName('quote-info')[0].innerText.replace(/\n/gi, '\t').split('\t').reduce((obj, el) => { const [key, value] = el.split("："); obj[key] = value; return obj; }, {})
                info['当前股价'] = price
                info['今日涨幅'] = stockChange[1]
                return info
            })
            item["股票代码"] = stockId
            item["股票名称"] = stocks[stockId]
            const PEJ = parseFloat(item['市盈率(静)'])
            const PED = parseFloat(item['市盈率(动)'])
            const PET = parseFloat(item['市盈率(TTM)'])
            if ([PEJ, PED, PET].every(el => !isNaN(el))) {
                if (PEJ < maxPE && PEJ > PET && PET > PED) {
                    item['PEJ/PET'] = PEJ / PET
                    item['PET/PED'] = PET / PED
                    matches.push(item)
                }
            }
            await page.waitForTimeout(10)
        }
    } catch {

    } finally {
        fs.writeFileSync('./match-stock.json', JSON.stringify(matches))
        const goodStock = oldMatch.filter(el => el['PEJ/PET'] > 1 && el['PET/PED'] > 1.2).map(el => ({
            "股票代码": el["股票代码"],
            "股票名称": el["股票名称"],
            "总市值": el["总市值"],
            "当前股价": el['当前股价'],
            "今日涨幅": el['今日涨幅'],
            "52周最高": el["52周最高"],
            "52周最低": el['"52周最低"'],
            "市盈率(静)": el["市盈率(静)"],
            "市盈率(TTM)": el["市盈率(TTM)"],
            "市盈率(动)": el["市盈率(动)"],
            "PEJ/PET": el["PEJ/PET"],
            "PET/PED": el["PET/PED"],
        }))
        const xls = json2xls(goodStock)
        fs.writeFileSync('./stock-good.xlsx', xls, 'binary')
        await browser.close()
    }
}
main()